<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item>监控管理</el-breadcrumb-item>
            <el-breadcrumb-item>监控服务列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- Prometheus 服务列表 -->
        <el-card class="box-card" style="margin-bottom: 10px;">
            <div slot="header">
                <span><i class="el-icon-coin"></i> Prometheus 数据源服务列表 (共 {{prometheusServiceCount}} 条)</span>
                <div style="float: right;">
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="openAddPrometheusServDialog" plain>添加 Prometheus 服务</el-button>
                    <el-button type="primary" icon="el-icon-refresh" size="mini" @click="refreshPrometheusList(true)" plain>刷新</el-button>
                </div>
            </div>
            <el-table :data="prometheusData" stripe>
                <el-table-column prop="ipaddr" label="服务地址" width="200px">
                    <template slot-scope="scope">
                        <el-link type="primary" style="font-size: 12px;" @click="openIFramePage(`http://${scope.row.ipaddr}:${scope.row.service_port}`)">
                            http://{{ scope.row.ipaddr }}:{{ scope.row.service_port }}
                        </el-link>
                    </template>
                </el-table-column>
                <el-table-column prop="user_normal" label="系统普通用户" width="120px"></el-table-column>
                <el-table-column prop="home_path" label="服务 HOME 路径"></el-table-column>
                <el-table-column label="操作" width="285px">
                    <template slot-scope="scope">
                        <el-dropdown size="mini" split-button type="success" @click="openIFramePage(`http://${scope.row.ipaddr}:${scope.row.service_port}`)" @command="openIFramePage">
                            浏览
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item icon="el-icon-pie-chart" :command="`http://${scope.row.ipaddr}:${scope.row.service_port}/graph`">Graph</el-dropdown-item>
                                <el-dropdown-item icon="el-icon-discover" :command="`http://${scope.row.ipaddr}:${scope.row.service_port}/tsdb-status`">TSDB Status</el-dropdown-item>
                                <el-dropdown-item icon="el-icon-collection-tag" :command="`http://${scope.row.ipaddr}:${scope.row.service_port}/flags`">Command-Line Flags</el-dropdown-item>
                                <el-dropdown-item icon="el-icon-thumb" :command="`http://${scope.row.ipaddr}:${scope.row.service_port}/rules`">Rules</el-dropdown-item>
                                <el-dropdown-item icon="el-icon-aim" :command="`http://${scope.row.ipaddr}:${scope.row.service_port}/targets`">Targets</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                        <el-dropdown size="mini" split-button type="primary" @click="prometheusConfigClick(scope.row.id)" @command="prometheusConfigCommand">
                            高级
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item icon="el-icon-document" :command="scope.row.id + '@@prometheus.yml'">prometheus.yml</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                        <el-button type="danger" icon="el-icon-delete-solid" size="mini" @click="removePrometheusService(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        
        <!-- Grafana 服务列表 -->
        <el-card class="box-card">
            <div slot="header">
                <span><i class="el-icon-pie-chart"></i> Grafana 图形服务列表 (共 {{grafanaServiceCount}} 条)</span>
                <div style="float: right;">
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="openAddGrafanaServDialog" plain>添加 Grafana 服务</el-button>
                    <el-button type="primary" icon="el-icon-refresh" size="mini" @click="refreshGrafanaList(true)" plain>刷新</el-button>
                </div>
            </div>
            <el-table :data="grafanaData" stripe>
                <el-table-column prop="ipaddr" label="服务地址" width="200px">
                    <template slot-scope="scope">
                        <el-link type="primary" style="font-size: 12px;" @click="openIFramePage(`http://${scope.row.ipaddr}:${scope.row.service_port}?kiosk`)">
                            http://{{ scope.row.ipaddr }}:{{ scope.row.service_port }}
                        </el-link>
                    </template>
                </el-table-column>
                <el-table-column prop="user_normal" label="系统普通用户" width="120px"></el-table-column>
                <el-table-column prop="home_path" label="服务 HOME 路径"></el-table-column>
                <el-table-column label="操作" width="285px">
                    <template slot-scope="scope">
                        <el-dropdown size="mini" split-button type="success" @click="openIFramePage(`http://${scope.row.ipaddr}:${scope.row.service_port}?kiosk`)" @command="openIFramePage">
                            浏览
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item icon="el-icon-s-home" :command="`http://${scope.row.ipaddr}:${scope.row.service_port}?kiosk`">Home</el-dropdown-item>
                                <el-dropdown-item icon="el-icon-coin" :command="`http://${scope.row.ipaddr}:${scope.row.service_port}/datasources?kiosk`">Data Sources</el-dropdown-item>
                                <el-dropdown-item icon="el-icon-bell" :command="`http://${scope.row.ipaddr}:${scope.row.service_port}/alerting?kiosk`">Alerting</el-dropdown-item>
                                <el-dropdown-item icon="el-icon-data-line" :command="`http://${scope.row.ipaddr}:${scope.row.service_port}/dashboards?kiosk`">Dashboards</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                        <el-dropdown size="mini" split-button type="primary" @click="grafanaConfigClick(scope.row.id)" @command="grafanaConfigCommand">
                            高级
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item icon="el-icon-document" :command="scope.row.id + '@conf@custom.ini'">conf/custom.ini</el-dropdown-item>
                                <el-dropdown-item icon="el-icon-document" :command="scope.row.id + '@conf@defaults.ini'">conf/defaults.ini</el-dropdown-item>
                                <el-dropdown-item icon="el-icon-document" :command="scope.row.id + '@conf@sample.ini'">conf/sample.ini</el-dropdown-item>
                                <el-dropdown-item icon="el-icon-coin" :command="scope.row.id + '@data@grafana.db'">data/grafana.db</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                        <el-button type="danger" icon="el-icon-delete-solid" size="mini" @click="removeGrafanaService(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 新增 Prometheus 数据源服务对话框 -->
        <el-dialog
            title="新增 Prometheus 数据源服务"
            :visible.sync="addPrometheusDialogVisible"
            width="900px"
            :show-close="false"
            :before-close="handleDialogClose">

            <el-form ref="prometheusAddFormRef" :model="prometheusAddForm" :rules="prometheusAddFormRules" label-width="150px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="服务IP地址" prop="ipaddr">
                            <el-input v-model="prometheusAddForm.ipaddr"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="SSH连接端口" prop="ssh_port">
                            <el-input-number v-model="prometheusAddForm.ssh_port" controls-position="right" :min="1" :max="65536"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="系统普通用户名" prop="user_normal">
                            <el-input v-model="prometheusAddForm.user_normal"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="系统管理员密码" prop="root_password">
                            <el-input v-model="prometheusAddForm.root_password" show-password></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="服务HOME路径" prop="home_path">
                    <el-input v-model="prometheusAddForm.home_path"></el-input>
                </el-form-item>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="数据源服务端口" prop="service_port">
                            <el-input-number v-model="prometheusAddForm.service_port" controls-position="right" :min="1" :max="65536"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="closeAddPrometheusServDialog">取 消</el-button>
                <el-button type="primary" @click="submitAddPrometheusServDialog">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 新增 Grafana 图形服务对话框 -->
        <el-dialog
            title="新增 Grafana 图形源服务"
            :visible.sync="addGrafanaDialogVisible"
            width="900px"
            :show-close="false"
            :before-close="handleDialogClose">

            <el-form ref="grafanaAddFormRef" :model="grafanaAddForm" :rules="grafanaAddFormRules" label-width="150px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="服务IP地址" prop="ipaddr">
                            <el-input v-model="grafanaAddForm.ipaddr"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="SSH连接端口" prop="ssh_port">
                            <el-input-number v-model="grafanaAddForm.ssh_port" controls-position="right" :min="1" :max="65536"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="系统普通用户名" prop="user_normal">
                            <el-input v-model="grafanaAddForm.user_normal"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="系统管理员密码" prop="root_password">
                            <el-input v-model="grafanaAddForm.root_password" show-password></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="服务HOME路径" prop="home_path">
                    <el-input v-model="grafanaAddForm.home_path"></el-input>
                </el-form-item>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="数据源服务端口" prop="service_port">
                            <el-input-number v-model="grafanaAddForm.service_port" controls-position="right" :min="1" :max="65536"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="closeAddGrafanaServDialog">取 消</el-button>
                <el-button type="primary" @click="submitAddGrafanaServDialog">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
export default {
    data: function () {
        var checkIpAddr = async (rule, value, callback) => {
            var ipCheckResult = this.$check_IpAddr(value);
            if (ipCheckResult) {
                callback(new Error(ipCheckResult));
            } else {
                callback();
            }
        }
        return {
            queryInfo: {
                query: '',
                pagenum: 1,
                pagesize: 9999
            },
            prometheusData: [],
            prometheusServiceCount: 0,
            grafanaData: [],
            grafanaServiceCount: 0,

            addPrometheusDialogVisible: false,
            addGrafanaDialogVisible: false,

            prometheusAddForm: {
                ipaddr: '',
                ssh_port: 22,
                user_normal: 'pgadmin',
                root_password: '123456',
                home_path: '/home/pgadmin/monitor/prometheus',
                service_port: 9090,
                targets: []
            },
            prometheusAddFormRules: {
                ipaddr: [
                    { required: true, message: '请输入服务IP地址', trigger: 'blur' },
                    { validator: checkIpAddr, trigger: 'blur' }
                ],
                ssh_port: [
                    { required: true, message: '请输入SSH监听端口号', trigger: 'blur' },
                    { type: 'number', message: '请输入正确的SSH监听端口号', trigger: ['blur', 'change'] }
                ],
                user_normal: [
                    { required: true, message: '请输入系统普通用户名', trigger: 'blur' }
                ],
                root_password: [
                    { required: true, message: '请输入系统管理员密码', trigger: 'blur' }
                ],
                home_path: [
                    { required: true, message: '请输入服务HOME路径', trigger: 'blur' }
                ],
                service_port: [
                    { required: true, message: '请输入服务端口号', trigger: 'blur' },
                    { type: 'number', message: '请输入正确服务端口号', trigger: ['blur', 'change'] }
                ]
            },
            grafanaAddForm: {
                ipaddr: '',
                ssh_port: 22,
                user_normal: 'pgadmin',
                root_password: '123456',
                home_path: '/home/pgadmin/monitor/grafana',
                service_port: 3000,
                datasources: []
            },
            grafanaAddFormRules: {
                ipaddr: [
                    { required: true, message: '请输入服务IP地址', trigger: 'blur' },
                    { validator: checkIpAddr, trigger: 'blur' }
                ],
                ssh_port: [
                    { required: true, message: '请输入SSH监听端口号', trigger: 'blur' },
                    { type: 'number', message: '请输入正确的SSH监听端口号', trigger: ['blur', 'change'] }
                ],
                user_normal: [
                    { required: true, message: '请输入系统普通用户名', trigger: 'blur' }
                ],
                root_password: [
                    { required: true, message: '请输入系统管理员密码', trigger: 'blur' }
                ],
                home_path: [
                    { required: true, message: '请输入服务HOME路径', trigger: 'blur' }
                ],
                service_port: [
                    { required: true, message: '请输入服务端口号', trigger: 'blur' },
                    { type: 'number', message: '请输入正确服务端口号', trigger: ['blur', 'change'] }
                ]
            }
        }
    },
    created: function () {
        this.getPrometheusList();
        this.getGrafanaList();
    },
    methods: {
        getPrometheusList: async function () {
            const result = await this.$http.get('prometheus', {
                params: this.queryInfo
            });
            const res = result.data;
            if (res.meta.status !== 200) return this.$message.error(`获取 Prometheus 数据源服务列表失败：${res.meta.msg}`);
            this.prometheusData = res.data.services;
            this.prometheusServiceCount = res.data.totalpage;
        },
        refreshPrometheusList: async function (showMessage) {
            await this.getPrometheusList();
            if (showMessage) this.$message.success(`刷新 Prometheus 数据源服务列表完成！`);
        },
        getGrafanaList: async function () {
            const result = await this.$http.get('grafana', {
                params: this.queryInfo
            });
            const res = result.data;
            if (res.meta.status !== 200) return this.$message.error(`获取 Grafana 图形服务列表失败：${res.meta.msg}`);
            this.grafanaData = res.data.services;
            this.grafanaServiceCount = res.data.totalpage;
        },
        refreshGrafanaList: async function (showMessage) {
            await this.getGrafanaList();
            if (showMessage) this.$message.success(`刷新 Grafana 图形服务列表完成！`);
        },
        openIFramePage: function (url) {
            this.$router.push({
                path: '/service/servicePage',
                query: {
                    url: url
                }
            });
        },
        handleDialogClose: function () {
        },
        openAddPrometheusServDialog: function () {
            this.addPrometheusDialogVisible = true;
        },
        openAddGrafanaServDialog: function () {
            this.addGrafanaDialogVisible = true;
        },
        closeAddPrometheusServDialog: function () {
            this.addPrometheusDialogVisible = false;
            this.$refs.prometheusAddFormRef.resetFields();
        },
        closeAddGrafanaServDialog: function () {
            this.addGrafanaDialogVisible = false;
            this.$refs.grafanaAddFormRef.resetFields();
        },
        submitAddPrometheusServDialog: function () {
            this.$refs.prometheusAddFormRef.validate(async valid => {
                if (!valid) return this.$message.warning(`Prometheus 服务参数信息校验失败，请检查参数信息有效性！`);
                const result = await this.$http.post(`prometheus`, this.prometheusAddForm);
                const res = result.data;
                if (res.meta.status !== 201) {
                    return this.$message.error(`新增 Prometheus 数据源服务失败: ${res.meta.msg}`);
                }
                this.$message.success(`新增 Prometheus 数据源服务成功！`);
                this.closeAddPrometheusServDialog();
                this.refreshPrometheusList();
            })
        },
        submitAddGrafanaServDialog: function () {
            this.$refs.grafanaAddFormRef.validate(async valid => {
                if (!valid) return this.$message.warning(`Grafana 服务参数信息校验失败，请检查参数信息有效性！`);
                const result = await this.$http.post(`grafana`, this.grafanaAddForm);
                const res = result.data;
                if (res.meta.status !== 201) {
                    return this.$message.error(`新增 Grafana 图形服务失败: ${res.meta.msg}`);
                }
                this.$message.success(`新增 Grafana 图形服务成功！`);
                this.closeAddGrafanaServDialog();
                this.refreshGrafanaList();
            })
        },
        removePrometheusService: async function (id) {
            const rm = await this.$confirm('Prometheus 数据源服务将从列表中移除，是否继续？', '确认', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'question'
            }).catch(err => err);
            if (rm !== 'confirm') return this.$message.info('已取消删除 Prometheus 操作。');

            const result = await this.$http.delete(`prometheus/${id}`);
            const res = result.data;
            if (res.meta.status !== 200) return this.$message.error(`删除 Prometheus 数据源服务失败: ${res.meta.msg}`);
            this.$message.success('删除 Prometheus 数据源服务成功');

            // 刷新 Prometheus 数据源服务列表
            this.getPrometheusList();
        },
        removeGrafanaService: async function (id) {
            const rm = await this.$confirm('Grafana 图形服务将从列表中移除，是否继续？', '确认', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'question'
            }).catch(err => err);
            if (rm !== 'confirm') return this.$message.info('已取消删除 Grafana 操作。');

            const result = await this.$http.delete(`grafana/${id}`);
            const res = result.data;
            if (res.meta.status !== 200) return this.$message.error(`删除 Grafana 图形服务失败: ${res.meta.msg}`);
            this.$message.success('删除 Grafana 图形服务成功');

            // 刷新 Grafana 图形服务列表
            this.getGrafanaList();
        },
        prometheusConfigClick: function (serviceId) {
            this.prometheusConfigCommand(`${serviceId}@@prometheus.yml`);
        },
        prometheusConfigCommand: function (command) {
            this.$router.push({
                path: '/service/prometheusConfig',
                query: {
                    command: command
                }
            });
        },
        grafanaConfigClick: function (serviceId) {
            this.grafanaConfigCommand(`${serviceId}@conf@custom.ini`);
        },
        grafanaConfigCommand: function (command) {
            this.$router.push({
                path: '/service/grafanaConfig',
                query: {
                    command: command
                }
            });
        }
    }
}
</script>

<style lang="less" scoped>
    .el-select,
    .el-input-number {
        width: 100%;
    }

    .el-dropdown {
        margin-left: 5px;
        margin-right: 5px;
    }
</style>